package edu.hubu.shop9.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.hubu.shop9.common.JsonResult;
import edu.hubu.shop9.entity.Product;
import edu.hubu.shop9.query.ProductQuery;
import edu.hubu.shop9.service.IProductService;
import edu.hubu.shop9.service.IProductTypeService;
import edu.hubu.shop9.service.ISystemDictionaryDetailService;
import edu.hubu.shop9.service.ISystemDictionaryTypeService;
import edu.hubu.shop9.util.ObjectUtils;
import edu.hubu.shop9.vo.ProductVo;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: waxijiang
 * @Date: 2021/7/26
 * @Content:
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    IProductService productService;

    @Autowired
    IProductTypeService productTypeService;

    @Autowired
    ISystemDictionaryTypeService systemDictionaryTypeService;

    @Autowired
    ISystemDictionaryDetailService systemDictionaryDetailService;

    @RequestMapping("selectAll")
    public String selectAll(Model model) {
        List<Product> list = productService.list();
        List<ProductVo> productVos = new ArrayList<>();
        for (Product p : list) {
            ProductVo vo = ObjectUtils.wrapperProduct(p, productTypeService, systemDictionaryTypeService,
                    systemDictionaryDetailService);
            productVos.add(vo);
        }
        model.addAttribute("list", productVos);
        return "product/productList";
    }


    @RequestMapping("/page")
    @ResponseBody
    public Map<String, Object> selectAll(ProductQuery query, int page, int rows) {
        Page<Product> page1 = new Page<>(page, rows);

        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        Map<String, Object> fields = ObjectUtils.getNotNullFields(query);
        // 构造like条件
        for (Map.Entry<String, Object> entry : fields.entrySet()) {
            if (!"".equals(entry.getValue())) {
                if (entry.getValue() instanceof String) {
                    wrapper.like(entry.getKey(), entry.getValue());
                } else if (entry.getValue() instanceof Integer) {
                    wrapper.eq(entry.getKey(), entry.getValue());
                }
            }
        }

        IPage<Product> pageInfo = productService.selectByQuery(wrapper, page1);
        List<ProductVo> productVos = new ArrayList<>();
        for (Product p : pageInfo.getRecords()) {
            ProductVo vo = ObjectUtils.wrapperProduct(p, productTypeService, systemDictionaryTypeService,
                    systemDictionaryDetailService);
            productVos.add(vo);
        }
        // 使用map传递到前台
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("rows", productVos);
        return resultMap;
    }


    @RequestMapping("/deleteByKey")
    @ResponseBody
    public JsonResult deleteByKey(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            productService.removeById(id);
            jsonResult.setMsg("已经删掉了");
        } catch (Exception e) {
            e.printStackTrace();
        }
//		使用map传递到前台
        return jsonResult;
    }


    @RequestMapping("/save")
    @ResponseBody
    public JsonResult save(Product product, @RequestParam("file") MultipartFile file) throws FileNotFoundException {
        product.setSmallpic(fileSave(file));
        JsonResult jsonResult = new JsonResult();
        try {
            productService.save(product);
            jsonResult.setMsg("添加成功");
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @RequestMapping("/update")
    @ResponseBody
    public JsonResult update(Product product, @RequestParam("file") MultipartFile file) throws FileNotFoundException {
        if (!"".equals(file.getOriginalFilename())) {
            product.setSmallpic(fileSave(file));
        }
        JsonResult jsonResult = new JsonResult();
        try {
            productService.updateById(product);
            jsonResult.setMsg("修改成功");
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    private String fileSave(MultipartFile file) throws FileNotFoundException {
        System.out.println("文件名:" + file.getOriginalFilename());
        System.out.println("文件类型:" + file.getContentType());
        System.out.println("文件大小:" + file.getSize());


        String targetDir = ResourceUtils.getURL("classpath:").getPath() + "static/upload";
        System.out.println(targetDir);
        String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
        File dir = new File(targetDir, dateDir);
        // 不存在则创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String newFileNamePrefix =
                new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString();
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String newFileName = newFileNamePrefix + "." + extension;
        File targetFile = new File(dir, newFileName);

        // 上传文件
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("上传成功");
        return "/upload/" + dateDir + "/" + newFileName;
    }
}
